<!--
 - MineAdmin is committed to providing solutions for quickly building web applications
 - Please view the LICENSE file that was distributed with this source code,
 - For the full copyright and license information.
 - Thank you very much for using MineAdmin.
 -
 - @Author X.Mo<root@imoi.cn>
 - @Link   https://gitee.com/xmo/mineadmin-vue
-->
<template>
  <ma-form-item
      v-if="(typeof props.component.display == 'undefined' || props.component.display === true)"
      :component="props.component"
      :custom-field="props.customField"
      :label="label"
  >
    <slot :name="`form-group-${props.component.dataIndex}`">
      <a-space>
        <template v-for="(component, componentIndex) in props.component?.formList ?? []" :key="componentIndex">
          <component
              :is="getComponentName(component?.formType ?? 'input')"
              :placeholder="component.placeholder ?? `请输入${component.title??''}`"
              v-model="formModel[component.dataIndex]"
              class="lg:gap-1"
              :component="component"
          >
            <template v-for="slot in Object.keys($slots)" #[slot]="component">
              <slot :name="slot" v-bind="component"/>
            </template>
          </component>
        </template>
      </a-space>
    </slot>
  </ma-form-item>
</template>

<script setup>
import {ref, inject, onMounted, watch, computed} from 'vue'
import {get, set} from 'lodash'
import MaFormItem from '../formItem/form-item.vue'
import {runEvent} from '../js/event.js'

const props = defineProps({
  component: Object,
  customField: {type: String, default: undefined}
})

const formModel = inject('formModel')
const getColumnService = inject('getColumnService')
const columns = inject('columns')
//后端传入数字类型导致报错 Invalid prop: type check failed for prop "modelValue". Expected String with value "0", got Number with value 0
const index = props.customField ?? props.component.dataIndex
const toVal = ref(`${get(formModel.value, index)}`);
const value = ref()
const label = computed(() => {
  if (props.component.title) {
    return props.component.title
  }
  if (typeof props.component?.formList[0] === 'undefined') {
    return 'un'
  }
  return props.component?.formList[0].title
})
if (toVal.value != 'undefined') {
  value.value = toVal.value
}
const rv = async (ev, value = undefined) => await runEvent(props.component, ev, {
  formModel,
  getColumnService,
  columns
}, value)
watch(() => get(formModel.value, index), vl => value.value = vl)
watch(() => value.value, v => {
  set(formModel.value, index, v)
  index.indexOf('.') > -1 && delete formModel.value[index]
})

const getComponentName = (formType) => {
  if (formType === 'input') {
    return 'a-input'
  } else if (formType === 'input-password') {
    return 'a-input-password'
  } else if (formType === 'input-search') {
    return 'a-input-search'
  } else {
    return 'a-input'
  }
}

rv('onCreated')
onMounted(() => rv('onMounted'))
</script>
